$(document).ready(function () {
  //页面加载完后再调用分类功能
  $.ajax({
    type: "GET",
    url: "/woniumall2/category/all",
    async: true,
    success: function (response) {
      showCategory(response);
    }
  });
  $("#list_order_details_list").hide(0);
  //颜色数组 并且自己调用实例化
  let table_color_array = new Array();
  function table_color_array_init() {
    table_color_array.push("table-primary");
    table_color_array.push("table-secondary");
    table_color_array.push("table-success");
    table_color_array.push("table-danger");
    table_color_array.push("table-warning");
    table_color_array.push("table-info");
    table_color_array.push("table-light");
    table_color_array.push("table-dark");
  }
  table_color_array_init();

  //搜索按钮
  $("#seach_btn").click(function () {
    let cartgory_Id = $("#btn_text").val();
    let serach_text = $("#search_text").val();
    let url = "/woniumall2/book.html?&bookname=" + serach_text;
    if (cartgory_Id != -1) {
      url = url + "&cartgory_Id=" + cartgory_Id;
    }
    let html_obj = {
      bookname: serach_text,
      cartgoryid: cartgory_Id
    };

    console.log(html_obj);
    window.sessionStorage.setItem("html_obj", JSON.stringify(html_obj));
    window.location.href = url;
  });


  let categoryId = -1;



  //设置当前的菜单分类
  function showCategory(response) {
    cartgory_li = response;
    $("#breadcrumb_ol").empty();
    $("#breadcrumb_ol").append($("<li class='breadcrumb-item'><a href='/woniumall2/book.html'>Home</a></li>"));
    let dropdown_item_list = $(".dropdown-item");
    //console.log(dropdown_item_list);
    $("#down_list").empty();

    for (let i = 0; i < response.length; i++) {
      let category = response[i];
      //菜单分类
      let li = $("<li></li>").prop("class", "breadcrumb-item").prop("id", "id" + (i + 1)).prop("value", category.id);


      let a = $("<a></a>").prop("href", "/woniumall2/book.html?categoryId=" + category.id).text(category.name);
      li.append(a);
      $("#breadcrumb_ol").append(li);

      //下拉按钮的值
      let down_li = $("<li></li>").prop("class", "dropdown-item").text(category.name);
      down_li.prop("value", category.id);
      down_li.click(function () {
        $("#btn_text").text(down_li.text());
        $("#btn_text").val(down_li.val());
      });
      //加入到下拉按钮
      $("#down_list").append(down_li);
      // <a class="dropdown-item" href="#">Another action</a>
    }
    $("#id" + categoryId).attr("class", "breadcrumb-item active");
    $("#a_id" + categoryId).removeAttr("href");
  }

  $ul = {
    category_find_goods: function (category_id) {
      $.ajax({
        url: "/woniumall2/goods/pages?categoryId=" + category_id + "&pageNum=1&pageSize=12",
        type: "GET",
        success: function (result) {
          categoryId = category_id;
          ol_li();
          showView(result);
        }
      });
    }
  }



  let order_data = "";
  let url = window.location.href;
  let personUrl = url.split("?");
  if (personUrl[1] == "personal") {
    //获取更多订单
    removeLiActive(list_content_list, list_content, list_more_order_list, list_more_order);
    sendAjax(1);
  }else if(personUrl[1] == "addAddress"){
    //新增地址
    removeLiActive(list_content_list, list_content, list_address_list, list_address);
  }
  else {
    //获取个人中心的数据
    centent_personal();
  }

  //获取个人中心的数据
  function centent_personal() {
    $.ajax({
      type: "POST",
      url: "/woniumall2/user/personal",
      success: function (responseResult) {
        console.log(responseResult);
        if (responseResult.data != null) {
          order_data = responseResult.data.orders;
          $("#user_name").text(responseResult.data.account);
         
          if(responseResult.data.avatar != null){
            $("#ico").attr("src", "/upload/" + responseResult.data.avatar);
          }else{
            $("#ico").attr("src", "/upload/user_ico.gif");
          }
          if (responseResult.data.orderNum != null) {
            $("#orderNum").text(responseResult.data.orderNum);
            console.log();
            if (responseResult.data.totalConsumption != null) {

              $("#totalConsumption").text("￥" + responseResult.data.totalConsumption);
            } else {
              $("#totalConsumption").text("￥" + "0");
            }
            $("#noEvaluateGoodsNums").text(responseResult.data.noEvaluateGoodsNums);
            $("#noPay").text("(" + responseResult.data.noPay + ")");
            $("#Pay").text("(" + responseResult.data.pay + ")");
          } else {
            $("#orderNum").text(0);
            $("#totalConsumption").text("￥" + 0);
            $("#noEvaluateGoodsNums").text(0);
            $("#noPay").text("(" + 0 + ")");
            $("#Pay").text("(" + 0 + ")");
          }


          table_show("#order_table", order_data);
        } else {
          //新用户

        }
      },

    });
  }

  //会员中心的table刷新
  $("#list_content_list").click(function () {
    centent_personal();
  });

 
  //li跳转方法
  function removeLiActive(li_list_remove, li_remove, li_list_add, li_add) {
    $(li_list_remove).removeClass("active");
    $(li_list_remove).removeClass("show");
    $(li_list_remove).attr("aria-selected", false);
    $(li_remove).removeClass("active");
    $(li_remove).removeClass("show");

    $(li_list_add).addClass("active");
    $(li_list_add).addClass("show");
    $(li_list_add).attr("aria-selected", true);
    $(li_add).addClass("active");
    $(li_add).addClass("show");
  }
  //跳转到订单详情的
  function go_order_detail(li_list_remove, li_remove, li_list_add, li_add) {
    $(li_list_remove).removeClass("active");
    $(li_list_remove).removeClass("show");
    $(li_list_remove).attr("aria-selected", false);
    $(li_remove).removeClass("active");
    $(li_remove).removeClass("show");

    $(li_list_add).addClass("active");
    $(li_list_add).attr("aria-selected", true);
    $(li_add).addClass("active");
    $(li_add).addClass("show");
  }

  //设置订单详情不可选
  $("#list_order_details_list").click(function () {
    if (isDisabled("#list_order_details_list")) {
      return;
    }
  });

  //更多订单
  $("#more_order").click(function () {
    removeLiActive(list_content_list, list_content, list_more_order_list, list_more_order);

    sendAjax(1);

  });


  //日期转换
  function parsDate(oldDate) {
    let date = new Date(oldDate);
    let year = date.getFullYear();
    let month = date.getMonth();
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();

    return year + "-" + (month + 1) + "-" + day + " " + hour + ":" + minute + ":" + second;
  }
  let is_refund = -1;
  //渲染详细订单的方法 需要传一个响应结果
  function go_orderDetatil(responseResult) {
    console.log(responseResult);
    $("#form_orderno").text(responseResult.data.orderno);

    $("#detati_date").text(parsDate(responseResult.data.ordertime));
    let detati_type = "";
    if (responseResult.data.status == "0") {
      //没有支付的
      detati_type = "待支付";
      $("#order_btn_list").empty();
      let cancel_order_btn = $("<button></button>").addClass("btn btn-outline-primary").prop("id", "cancel_order").text("取消订单");

      //取消订单按钮
      cancel_order_btn.click(function () {
        if (confirm("确认取消该订单？")) {
          let form_orderno = $("#form_orderno").text();
          $.ajax({
            type: "POST",
            url: "/woniumall2/order/cancelOrder",
            data: {
              orderno: form_orderno
            },
            success: function (responseResult) {
              if (responseResult.status == "CANCEL_ORDER_SUCCESS") {
                alert(responseResult.message);
                removeLiActive(list_order_details_list, list_order_details, list_more_order_list, list_more_order);
                sendAjax(1);
              } else {
                alert(responseResult.message);
              }
            }
          });
        } else {
          return;
        }

      });

      let go_pay_btn = $("<button></button>").addClass("btn btn-outline-danger").prop("id", "go_pay").prop("type", "submit").text("立即支付");
      
      //立即支付方法

      go_pay_btn.click(function () {
        console.log("被点击");
        $("#payfrom").submit();
      });

      $("#order_btn_list").append(cancel_order_btn);

      $("#order_btn_list").append(go_pay_btn);

    } else if (responseResult.data.status == "1") {
      //如果是待收货 可以确认收货
      detati_type = "待收货";
      $("#order_btn_list").empty();

      let confirm_order_btn = $("<button></button>").addClass("btn btn-outline-primary").prop("id", "confirm_order").text("确认收货");
      let refund_btn = $("<button></button>").addClass("btn btn-outline-danger").prop("id", "refund").prop("type", "submit").text("退款 不买了");
      
      is_refund = 1;
      
      let orderno = responseResult.data.orderno;
      //确认全部收货
      confirm_order_btn.click(function () {
        if (confirm("是否确认全部收货")) {
          //确认全部收货
          //发送订单号过去修改状态
          $.ajax({
            url: "/woniumall2/order/confirmReceiving",
            type: "post",
            data: {
              "orderno": orderno,
            },
            success: function (responseResult) {
              if (responseResult.status == "SUCCESS") {
                //console.log(responseResult);
                //console.log("正在执行");
                //确认收货成功 
                //刷新当前的
                //发送请求 调用方法 刷新当前方法
                $.ajax({
                  type: "POST",
                  url: "/woniumall2/order/details",
                  data: {
                    "orderno": orderno,
                  },
                  success: function (responseResult) {
                    //调用去订单详情的方法
                    if (responseResult.status == "SELECT_SUCCESS") {
                      go_orderDetatil(responseResult);
                      return;
                    }
                    
                    
                  }
                });
                return;
              } else {

              }
            },

          });
        } else {
          return;
        }


      })

      //退钱

      refund_btn.click(function(){
        //获得order的编号  
        $('#refund_modal').modal('show');
        $.ajax({
          type:"POSt",
          url:"/woniumall2/order/refund",
          data:{
            "orderno":responseResult.data.orderno
          },
          success:function(responseResult){
            //获得后台的数据 然后封装成对象 再删除
            console.log(responseResult);
            if(responseResult.status == "SUCCESS"){
              //成功后 发送ajax去取消订单
              let refund = responseResult.data;
              $.ajax({
                type:"POSt",
                url:"/woniumall2/pay/refund",
                data:{
                  "orderno":refund.orderno,
                  "user_no":refund.tradeno,
                  "refund_money":refund.money,
                },
                success:function(responseResult){
                  console.log(responseResult);
                  if(responseResult.status == "SUCCESS"){
                    //如果退款成功
                    $("#refund_text").text("退款成功 正在退出 退款" + responseResult.data + "元");
                   window.setInterval(function quit_refund(){
                    $('#refund_modal').modal('hide');
                   },2000);

                   //跳到订单详情
                   removeLiActive(list_order_details_list, list_order_details, list_more_order_list, list_more_order);
                   sendAjax(1);
                   
                  }else{
                    //退款失败
                    $("#refund_text").text("退款失败 稍后再试 正在退出");
                    window.setInterval(function quit_refund(){
                      
                      $('#refund_modal').modal('hide');
                     },2000);
                  }


                }

              });

            
              // window.localStorage.setItem("refund",JSON.stringify(responseResult.data));
              // window.location.href = "/woniumall2/test3.html";
            }
          }
        })
      })


      $("#order_btn_list").append(confirm_order_btn);
      $("#order_btn_list").append(refund_btn);

    } else if (responseResult.data.status == "2") {
      $("#order_btn_list").empty();
      detati_type = "订单完成";
    } else if (responseResult.data.status == "3") {
      $("#order_btn_list").empty();
      detati_type = "订单结束了 可以查看自己的评价";
    }

    $("#detati_type").text(detati_type);

    $("#table_order_accept").text(responseResult.data.accept);

    $("#table_order_address").text(responseResult.data.address);

    $("#table_order_tel").text(responseResult.data.telphone);

    $("#shop_table").empty();

    //渲染shop_table

    let money = 0;

    for (let i = 0; i < responseResult.data.orderItemDtos.length; i++) {
      let orderItemDto = responseResult.data.orderItemDtos[i];
      let img_td = $("<td></td>");
      let img = $("<img>").prop("src", "../"
        + orderItemDto.image).addClass("images");
      img_td.append(img);

      let goodsName_td = $("<td></td>");
      if (orderItemDto.name.length < 25) {
        goodsName_td.text(orderItemDto.name);
        goodsName_td.prop("title", orderItemDto.name);

      } else {
        goodsName_td.text((orderItemDto.name).substring(0, 25) + "...");
        goodsName_td.prop("title", orderItemDto.name);
      }


      let goodsPrice_td = $("<td></td>").text(orderItemDto.price);

      let goodsNums_td = $("<td></td>").text(orderItemDto.nums);
      let prices_td = $("<td></td>");
      prices_td.text((orderItemDto.nums * orderItemDto.price).toFixed(2));

      let isEvaluate_td = $("<td></td>");
      //根据支付状态来设置
      if (responseResult.data.status == "0") {
        isEvaluate_td.text("等待支付订单");
      } else if (responseResult.data.status == "2") {
        //如果是2 说明确认确认收货 可以评价了
        let a_go_evaluate = $("<a></a>").prop("href", "#");

        if (orderItemDto.evaluate == 1) {
          a_go_evaluate.text("待评价");
          a_go_evaluate.attr("value", "1");
        } else if (orderItemDto.evaluate == 2) {
          a_go_evaluate.text("已评价");
          a_go_evaluate.attr("value", "2");
        }

        if (a_go_evaluate.attr("value") == '1') {
          //如果是1 就可以去评价
          a_go_evaluate.click(function () {
            if (confirm("是否去评价此商品")) {
              //如果为是
              let orderItem = {
                goodsid: orderItemDto.goodsId,
                orderItemId: orderItemDto.orderItemId
              }
              window.localStorage.setItem("orderItem", JSON.stringify(orderItem));
              window.location.href = "/woniumall2/bookMessage.html?goodsid=" + orderItemDto.goodsId;
            } else {
              //如果不是
              return;
            }
          });

        } else if (a_go_evaluate.attr("value") == '2') {
          //如果是2 就只能查看评价
          a_go_evaluate.click(function () {
            if (confirm("查看自己的评价")) {
              //发送请求查看自己的评论
              $("#alert_remark").show();
              $("#alert_remark_send").hide();
              $.ajax({
                url: "/woniumall2/remark/getRemark",
                type: "POST",
                data: {
                  "orderItemId": orderItemDto.orderItemId,
                  "goodsid": orderItemDto.goodsId,
                },
                success: function (responseResult) {
                  console.log(responseResult);
                  //
                  if (responseResult.status == "SELECT_SUCCESS") {
                    //有数据 就渲染
                    let remark = responseResult.data.data[0];
                    console.log(remark);
                    console.log("SELECT_SUCCESS");
                    // $("#ta").removeAttr("disabled");
                    $("#content_remark").html(remark.content).emoticonize(true).show();
                    $("#ta").hide();
                    content = remark.content;
                    remark_id = remark.id;
                  }
                }

              });
              $("#remark_connent").modal("show");

            } else {
              //如果不是
            }
          });
        }
        //评论加入到当前
        isEvaluate_td.append(a_go_evaluate);

      } else if (responseResult.data.status == "1") {
        //如果是1 可以确认收货
        //如果是待收货 可以确认收货

        if (orderItemDto.evaluate == 0) {
          //判断当前状态为0 说明
          //没有收货 那么可以加上按钮 来确认收货
          let order_success_btn = $("<button></button>").addClass("btn btn-outline-primary").prop("id", "order_success_btn").text("确认收货");

          //取消订单按钮


          let orderno = responseResult.data.orderno;
          //点击事件 更改自己的为确认收货
          order_success_btn.click(function () {

            $.ajax({
              type: "post",
              url: "/woniumall2/orderItem/updateEvaluate",
              data: {
                "orderItemId": orderItemDto.orderItemId,
                "evaluateType": '1'
              },
              success: function (responseResult) {
                console.log(orderno);

                //确定单个收件 然后刷新页面
                if (responseResult.status == "SUCCESS") {
                  // ajax_detailOrderno(orderno);
                  $.ajax({
                    type: "POST",
                    url: "/woniumall2/order/details",
                    data: {
                      "orderno": orderno,
                    },
                    success: function (responseResult) {
                      //调用去订单详情的方法
                      go_orderDetatil(responseResult);
                      return;
                    }
                  });
                }
              }
            });
          });



          isEvaluate_td.append(order_success_btn);
        } else if (orderItemDto.evaluate == 1) {
          //如果是已经收货 那么不可以退款
          if(is_refund == 1){
            //说明有这个按钮则删除
            $("#refund").hide();
          }
          
          let a_go_evaluate = $("<a></a>").prop("href", "#");

          if (orderItemDto.evaluate == 1) {
            a_go_evaluate.text("待评价");
            a_go_evaluate.attr("value", "1");
          } else if (orderItemDto.evaluate == 2) {
            a_go_evaluate.text("已评价");
            a_go_evaluate.attr("value", "2");
          }
          //如果是1 就可以去评价
          a_go_evaluate.click(function () {
            if (confirm("是否去评价此商品")) {
              //如果为是
              let orderItem = {
                goodsid: orderItemDto.goodsId,
                orderItemId: orderItemDto.orderItemId
              }
              window.localStorage.setItem("orderItem", JSON.stringify(orderItem));
              window.location.href = "/woniumall2/bookMessage.html?goodsid=" + orderItemDto.goodsId;
            } else {
              //如果不是
              return;
            }
          });
          //评论加入到当前
          isEvaluate_td.append(a_go_evaluate);

        } else if (orderItemDto.evaluate == 2) {
          //评价完成
          //如果是2 就只能查看评价
          let a_go_evaluate = $("<a></a>").prop("href", "#");

          if (orderItemDto.evaluate == 1) {
            a_go_evaluate.text("待评价");
            a_go_evaluate.attr("value", "1");
          } else if (orderItemDto.evaluate == 2) {
            a_go_evaluate.text("已评价");
            a_go_evaluate.attr("value", "2");
          }
          a_go_evaluate.click(function () {
            if (confirm("查看自己的评价")) {
              //发送请求查看自己的评论
              $("#alert_remark").show();
              $("#alert_remark_send").hide();
              $.ajax({
                url: "/woniumall2/remark/getRemark",
                type: "POST",
                data: {
                  "orderItemId": orderItemDto.orderItemId,
                  "goodsid": orderItemDto.goodsId,
                },
                success: function (responseResult) {
                  console.log(responseResult);
                  //
                  if (responseResult.status == "SELECT_SUCCESS") {
                    //有数据 就渲染
                    let remark = responseResult.data.data[0];
                    console.log(remark);
                    console.log("SELECT_SUCCESS");
                    // $("#ta").removeAttr("disabled");
                    $("#content_remark").html(remark.content).emoticonize(true).show();
                    $("#ta").hide();
                    content = remark.content;
                    remark_id = remark.id;
                  }
                }

              });
              $("#remark_connent").modal("show");

            } else {
              //如果不是
            }
          });
          //评论加入到当前
          isEvaluate_td.append(a_go_evaluate);
        }
      } else if (responseResult.data.status == "3") {
        //评价完成
        //如果是2 就只能查看评价
        let a_go_evaluate = $("<a></a>").prop("href", "#");

        if (orderItemDto.evaluate == 1) {
          a_go_evaluate.text("待评价");
          a_go_evaluate.attr("value", "1");
        } else if (orderItemDto.evaluate == 2) {
          a_go_evaluate.text("已评价");
          a_go_evaluate.attr("value", "2");
        }

        a_go_evaluate.click(function () {
          if (confirm("查看自己的评价")) {
            //发送请求查看自己的评论
            $("#alert_remark").show();
            $("#alert_remark_send").hide();
            $.ajax({
              url: "/woniumall2/remark/getRemark",
              type: "POST",
              data: {
                "orderItemId": orderItemDto.orderItemId,
                "goodsid": orderItemDto.goodsId,
              },
              success: function (responseResult) {
                console.log(responseResult);
                //
                if (responseResult.status == "SELECT_SUCCESS") {
                  //有数据 就渲染
                  let remark = responseResult.data.data[0];
                  console.log(remark);
                  console.log("SELECT_SUCCESS");
                  // $("#ta").removeAttr("disabled");
                  $("#content_remark").html(remark.content).emoticonize(true).show();
                  $("#ta").hide();
                  content = remark.content;
                  remark_id = remark.id;
                }
              }

            });
            $("#remark_connent").modal("show");

          } else {
            //如果不是
          }
        });
        isEvaluate_td.append(a_go_evaluate);
      }





      let tr = $("<tr></tr>");
      tr.addClass(table_color_array[randomNum(0, 7)]);

      tr.append(img_td);
      tr.append(goodsName_td);
      tr.append(goodsPrice_td);
      tr.append(goodsNums_td);
      tr.append(prices_td);
      tr.append(isEvaluate_td);

      money += (orderItemDto.nums * orderItemDto.price);
      console.log(money);

      $("#shop_table").append(tr);

    }
    $("#over_money").text(money.toFixed(2));

    $("#order_no").val(responseResult.data.orderno);
    $("#order_money").val(money.toFixed(2));
    $("#order_name").val(30);
  }

  //修改评论

  let content = null;

  //修改评论的按钮 把自己变成发送按钮
  $("#alert_remark").click(function () {

    $("#content_remark").hide();

    $("#ta").show();
    $("#ta").removeAttr("disabled");
    $("#ta").html(content).emoticonize(true).show();

    $("#alert_remark").hide();
    $("#alert_remark_send").show();
  });

  //真正的修改按钮
  let remark_id = null;
  //真正的修改评论按钮
  $("#alert_remark_send").click(function () {
    let ta_content = $("#ta").val();
    if (content == ta_content) {
      //说明一样 没有修改
      $("#ta").hide();
      $("#content_remark").show();
      $("#content_remark").html(content).emoticonize(true).show();

      $("#alert_remark_send").hide();
      $("#alert_remark").show();
      return;
    }
    if (content.length != 0) {
      $.ajax({
        type: "post",
        url: "/woniumall2/remark/updateRemark",
        data: {
          "remarkid": remark_id,
          "content": ta_content
        },
        success: function (responseResult) {
          console.log(responseResult);
          if (responseResult.status == "SELECT_SUCCESS") {
            //修改成功
            console.log("//修改成功");
            $("#content_remark").html(responseResult.data).emoticonize(true).show();
            $("#ta").hide();
            $("#content_remark").show();

            $("#alert_remark_send").hide();
            $("#alert_remark").show();

          } else {
            //修改失败
            $("#alert_remark_send").hide();
            $("#alert_remark").show();
            $("#ta").hide();
            $("#content_remark").show();
          }
        }
      })
    } else {
      alert("不能为空");
    }
  })



  //当被关闭的时候
  $('#remark_connent').on('hidden.bs.modal', function (e) {
    $("#alert_remark_send").hide();
    $("#alert_remark").show();
    $("#ta").hide();
    $("#content_remark").show();
  });
  //发送数据刷新当前的订单详情页面
  function ajax_detailOrderno(orderno) {

  }
  //显示在表格上的方法
  function table_show(table_name, order_data_now) {
    $(table_name).empty();
    for (let i = 0; i < order_data_now.length; i++) {
      let order = order_data_now[i];
      let td_orderno = $("<td><a></a></td>").text(order.orderno).prop("class", "text-danger ");

      //如果是订单详情里面进来的
      if (table_name == "#order_table_more") {
        td_orderno.click(function () {
          $.ajax({
            type: "POST",
            url: "/woniumall2/order/details",
            data: {
              orderno: td_orderno.text()
            },
            success: function (responseResult) {
              //调用去订单详情的方法
              go_orderDetatil(responseResult);
            }
          });
          go_order_detail(list_more_order_list, list_more_order, list_order_details_list, list_order_details);
        });


      }
      //如果是个人中心进来的
      if (table_name == "#order_table") {
        td_orderno.click(function () {
          $.ajax({
            type: "POST",
            url: "/woniumall2/order/details",
            data: {
              orderno: td_orderno.text()
            },
            success: function (responseResult) {

              go_orderDetatil(responseResult);
            }
          });

          go_order_detail(list_content_list, list_content, list_order_details_list, list_order_details);
        });


      }

      let td_ordertime = $("<td></td>").text(parsDate(order.ordertime));

      let td_accept = $("<td></td>").text(order.accept);
      if (order.paytype == '1') {
        order.paytype = "微信";
      } else if (order.paytype == '2') {
        order.paytype = "支付宝";
      }
      let td_paytype = $("<td></td>").text(order.paytype);
      let td_money = $("<td></td>").text(order.money);
      if (order.status == '0') {
        order.status = "待支付";
      } else if (order.status == '1') {
        order.status = "待收货";
      } else if (order.status == '2') {
        order.status = "待评价";
      } else if (order.status == '3') {
        order.status = "评价完成";
      }
      let td_status = $("<td></td>").text(order.status);


      let tr = $("<tr></tr>")
      tr.addClass(table_color_array[randomNum(0, 7)]);

      tr.append(td_orderno);
      tr.append(td_ordertime);
      tr.append(td_accept);
      tr.append(td_paytype);
      tr.append(td_money);
      tr.append(td_status);
      $(table_name).append(tr);
    }
  }



  //页数渲染
  function page(responseResult) {
    //设置当前页
    $("#current_page").text(responseResult.data.currentPage);
    //如果小于等于1 那么设置为不可点击
    if ($("#current_page").text() <= 1  ) {
      $("#prev_li").addClass("disabled");
    }
    if(responseResult.data.totalPage == 1){
      $("#next_li").addClass("disabled");
    }
    //计算总价
    $("#total_page").text(responseResult.data.totalPage);
    table_show("#order_table_more", responseResult.data.data);
  }


  //发送请求的方法
  function sendAjax(current_page) {
    $.ajax({
      type: "POST",
      url: "/woniumall2/order/page",
      data: {
        pageSize: 5,
        pageNum: current_page,
      },
      success: function (responseResult) {
        page(responseResult);
      }
    });
  }

  $("#list_more_order_list").click(function () {
    sendAjax(1);
  })





  //下一页
  $("#next").click(function () {
    let current_page = $("#current_page").text();
    current_page++;
    if (current_page >= $("#total_page").text()) {
      $("#next_li").addClass("disabled");
      sendAjax(current_page);
      return;
    }
    $("#prev_li").removeClass("disabled");
    sendAjax(current_page);
  });

  //上一页
  $("#prev").click(function () {
    let current_page = $("#current_page").text();
    current_page--;
    if (current_page <= 1) {
      $("#prev_li").addClass("disabled");
      sendAjax(current_page);
      return;
    }
    $("#next_li").removeClass("disabled");

    sendAjax(current_page);
  });

  //首页
  $("#first").click(function () {
    $("#prev_li").addClass("disabled");
    $("#next_li").removeClass("disabled");
    sendAjax(1);
  });


  //尾页
  $("#end").click(function () {
    let current_page = $("#total_page").text();
    $("#prev_li").removeClass("disabled");
    $("#next_li").addClass("disabled");
    sendAjax(current_page);
  });

  //开始搜索时显示确定按钮
  $("#goPage").on("input", function () {
    let page = $("#goPage").val();
    if (page.length > 0) {
      $("#page_btn").removeClass("fade");
    } else {
      $("#page_btn").addClass("fade");
    }
  });


  //去到指定页数
  $("#go_page").click(function () {
    if (isDisabled("#go_page")) {
      return;
    }
    let gopage = $("#goPage").val();
    if (gopage == "") {
      return;
    }
    let max_page = $("#total_page").text();
    console.log(max_page);
    if (gopage <= 1) {
      gopage = 1;
      $("#prev_li").addClass("disabled");
      $("#next_li").removeClass("disabled");
    } else if (JSON.parse(gopage) > JSON.parse(max_page)) {
      gopage = max_page;
      console.log(gopage);
      $("#prev_li").removeClass("disabled");
      $("#next_li").addClass("disabled");
    }
    $("#goPage").val("");
    sendAjax(gopage);
    $("#page_btn").addClass("fade");
  });






  //更新密码的提示
  // $("#updatePassword_from").bootstrapValidator({
  //   message: 'This value is not valid',
  //   feedbackIcons: {
  //     valid: 'glyphicon glyphicon-ok',
  //     invalid: 'glyphicon glyphicon-remove',
  //     validating: 'glyphicon glyphicon-refresh'
  //   },
  //   fields: {

  //     password_update: {
  //       message: '密码无效',
  //       validators: {
  //         notEmpty: {
  //           message: '密码不能为空'
  //         },
  //         stringLength: {
  //           min: 6,
  //           max: 30,
  //           message: '密码长度必须在6到30之间'
  //         },
  //         identical: { //相同
  //           field: 'password_update',
  //           message: '两次密码不一致'
  //         },
  //         different: { //不能和用户名相同
  //           field: 'username',
  //           message: '不能和用户名相同'
  //         },
  //         regexp: { //匹配规则
  //           regexp: /^[a-zA-Z0-9_\.]+$/,
  //           message: 'The username can only consist of alphabetical, number, dot and underscore'
  //         }
  //       }
  //     },
  //     password_update_repassword: {
  //       message: '密码无效',
  //       validators: {
  //         identical: { //相同
  //           field: 'password_update',
  //           message: '两次密码不一致'
  //         }
  //       }
  //     },
  //   }
  // });


  let password = "";
  // 密码校验
  $("#upPwd_btn").click(function () {
    if (isDisabled("#upPwd_btn")) {
      return;
    }
    $("#exampleModal").attr("aria-hidden", "true").attr("data-backdrop", "static");
    $("#exampleModal").modal({ keyboard: false });
  });
  //发送密码 如果成功 则可以修改密码
  let account = null;
  $("#send_updatePassword").click(function () {
    let oldPwd = $("#recipient_old_password").val();
    $("#recipient_old_password").val("");
    $.ajax({
      type: "POST",
      url: "/woniumall2/user/update",
      data: {
        oldPwd: oldPwd
      },
      success: function (responseResult) {
        if (responseResult.status == "PWD_RIGHT") {
          account = responseResult.data;
          console.log(account);
          $("#exampleModal").modal('hide');
          $("#upPwd_btn").addClass('fade disabled');
          $("#upPwd_btn").removeAttr("data-target");
          $("#upPwd_btn").hide(0);

          $("#uodate_div").removeClass("fade");
          $("#cancel_password").removeClass("fade disabled");
          password = oldPwd;
        } else if (responseResult.status == "PWD_ERROE") {
          // $("#exampleModal").modal('hide');
          $("#tpi_upPwd").text(responseResult.message);
          timer_add();
          let div = $("div:last");
          console.log(div);
        }
      }
    });

  });
  //更改密码
  //password_update

  //定时器
  function timer_add() {
    setTimeout(() => {
      $("#tpi_upPwd").addClass("fade");
    }, 2000);
  }


  //如果密码不相同 不能点击提交按钮
  $("#password_update_repassword").on("input", function () {
    let pwdTwo = $("#password_update_repassword").val();
    let pwdOne = $("#password_update").val();

    //如果密码相同
    if (pwdTwo == pwdOne) {
      $("#update_password_btn").removeClass("disabled");

      $("#password_update_repassword").removeClass("is-invalid");
      $("#password_update_repassword").addClass("is-valid");
      $("#res_pwd").addClass("valid-feedback")
      $("#res_pwd").text("");
    } else {
      //与上面个密码不相同
      $("#update_password_btn").addClass("disabled");

      $("#password_update_repassword").removeClass("is-valid");
      $("#password_update_repassword").addClass("is-invalid");
      $("#res_pwd").addClass("invalid-feedback")
      $("#res_pwd").text("两次密码不一致");


    }
  });

  //只要有值就会显示按钮
  $("#password_update").on("input", function () {
    let pwdOne = $("#password_update").val();
    //如果新旧密码相同
    if (pwdOne == password) {
      $("#no_old_pwd").text("不能和之前的密码一样");
      $("#update_password_btn").addClass("fade");
      return;
    }
    //如果密码不为空
    if (pwdOne.length < 6) {
      //如果密码为空
      //提示
      $("#password_update").removeClass("is-valid");
      $("#password_update").addClass("is-invalid");
      $("#no_old_pwd").addClass("invalid-feedback")
      $("#no_old_pwd").text("密码不能小于6位数");
      $("#update_password_btn").addClass("fade");
    } else {

      $("#update_password_btn").removeClass("fade");


      $("#password_update").removeClass("is-invalid");
      $("#password_update").addClass("is-valid");
      $("#no_old_pwd").addClass("valid-feedback")
      $("#no_old_pwd").text(" ");

    }
  });

  //更改密码

  $("#update_password_btn").click(function () {
    if (isDisabled("#update_password_btn")) {
      return;
    }
    let password = $("#password_update").val();
    $.ajax({
      type: "POST",
      url: "/woniumall2/user/updatePassword",
      data: {
        "password": password,
        "account": account
      },
      success: function (responseResult) {
        console.log(responseResult);
        if (responseResult.status == "UPDATE_PASSWORD_SUCCESS") {
          alert("密码修改成功 请重新登陆");
          //关闭定时器
          clearInterval(timer);

          //删除cookie
          $.removeCookie('account', { path: '/' });

          window.localStorage.removeItem("account");




          window.location.href = "../../index.html";
        } else {
          alert(responseResult.message);
        }
      }
    });
  });




  //取消更改密码
  //cancel_password
  $("#cancel_password").click(function () {
    //list_content_list
    //list-settings-list
    if (isDisabled("#cancel_password")) {
      return;
    }
    removeLiActive(list_update_password_list, list_update_password, list_content_list, list_content);
    $("#upPwd_btn").attr("data-target", "#exampleModal");
    $("#upPwd_btn").removeClass("fade disabled");
    $("#upPwd_btn").show(0);


    $("#uodate_div").addClass("fade");
    $("#update_password_btn").addClass("fade disabled");
    $("#cancel_password").addClass("fade disabled");
  });

  $("#list_update_password_list").click(function () {
    $("#upPwd_btn").attr("data-target", "#exampleModal");
    $("#upPwd_btn").removeClass("fade disabled");
    $("#upPwd_btn").show(0);

    $("#uodate_div").addClass("fade");
    $("#update_password_btn").addClass("fade disabled");
    $("#cancel_password").addClass("fade disabled");
  });



  //获得地址
  $("#list_address_list").click(function () {
    addAddressTable();
  });

  let old_accept = null;
  let old_province = null;
  let old_city = null;
  let old_area = null;
  let old_address_td = null;
  let old_telphone = null;

  let old_address = "";
  //渲染地址
  function addAddressTable() {
    $.ajax({
      type: "POST",
      url: "/woniumall2/address/all",
      success: function (responseResult) {
        // console.log(responseResult);
        if (responseResult.status == "SUCCESS") {
          $("#address_tbody").empty();
          for (let i = 0; i < responseResult.data.length; i++) {
            let address = responseResult.data[i];

            let accept_td = $("<td></td>").text(address.accept);


            let province_td = $("<td></td>").text(address.province + address.city + address.area);



            let address_td = $("<td></td>").text(address.address);


            let telphone_td = $("<td></td>").text(address.telphone);


            let span = $("<span></span>").text(" | ");
            let span2 = $("<span></span>").text(" | ");

            let type_td = $("<td></td>");

            let alert_a = $("<a></a>").text("修改").prop("href", "#").prop("id", "alert_address").attr("data-toggle", "modal").attr("data-target", "#address_model");

            //更改地址
            alert_a.click(function () {
              $("#address_model").attr("aria-hidden", "true").attr("data-backdrop", "static");
              $("#alert_accept_name").val(accept_td.text());
              $("#alert_address_now").val(address.address);

              $("#alert_telphone").val(address.telphone);

              $("#quit_btn").val(address.id);

              old_accept = address.accept;
              old_province = address.province;
              old_city = address.city;
              old_area = address.area;
              old_address_td = address.address;
              old_telphone = address.telphone;

              //选择省 先初始化 加上请选择省占位置
              $("#province").empty();
              let index = -1;
              //$("#province").append("<option value='-1'>请选择省</option>");
              //遍历加入 对比相同 记录下下标
              for (let i = 0; i < provinceList.length; i++) {
                let province = provinceList[i];
                let provinceName = province.name;
                provinceArray[i] = provinceName;
                $("#province").append(new Option(provinceName, i + 1))
                //console.log(provinceName);
                if (provinceName == address.province) {
                  index = i;
                }
              }
              provinceName = address.province;
              $("#province").val(index + 1);

              //清空city 加上占位的 遍历city 
              $("#city").empty();
              //$("#city").append("<option value='-1'>请选择市</option>");
              //遍历城市对比 记录下标
              for (let n = 0; n < provinceList.length; n++) {
                let provice = provinceList[n];
                if (provice.name == provinceName) {
                  cityList = provice.cityList;
                  cityTag.innerHTML = "";
                  for (let c = 0; c < cityList.length; c++) {
                    let city = cityList[c];
                    let cityName = city.name;
                    cityArray[c] = cityName;

                    $("#city").append(new Option(cityName, c));
                    if (cityName == address.city) {
                      index = c;
                    }
                  }
                }
              }
              //设置city默认值
              $("#city").val(index);

              //获取城市当前的下标
              let city1 = cityList[0];
              let areaList = city1.areaList;
              areaTag.innerHTML = "";

              //设置为空 
              $("#area").empty();
              // $("#area").append("<option value='-1'>请选择区</option>");

              //遍历对比 记录下标
              for (let a = 0; a < areaList.length; a++) {
                let area = areaList[a];
                $("#area").append(new Option(area, a));
                if (area == address.area) {
                  index = a;
                }
              }

              //设置区的默认值
              $("#area").val((index));

            });

            if (address.type == "y") {

              let alert_default_a = $("<span></span>").text("默认地址");
              old_address = address.id;


              type_td.append(alert_a);
              type_td.append(span);
              type_td.append(alert_default_a);

            } else {

              let delete_a = $("<a></a>").text("删除").prop("href", "#").prop("id", "delete_address");

              delete_a.click(function () {
                //删除地址
                if (confirm("确定删除该地址？")) {
                  $.ajax({
                    type: "POST",
                    url: "/woniumall2/address/delAddress",
                    data: {
                      addressId: address.id,
                    },
                    success: function (responseResult) {
                      console.log(responseResult);
                      addAddressTable();
                    },
                  });
                } else {
                  return;
                }
              });


              let alert_default_a = $("<a></a>").text("设为默认").prop("href", "#").prop("id", "default_address");

              alert_default_a.click(function () {
                //更改默认地址 把之前的旧地址传过去

                $.ajax({
                  type: "POST",
                  url: "/woniumall2/address/setDefaultAddress",
                  data: {
                    oldId: old_address,
                    oldType: "y",
                    newId: address.id,
                    newType: "n",
                  },
                  success: function (responseResult) {
                    console.log(responseResult);
                    if (responseResult.status == "SUCCESS") {
                      addAddressTable();
                    } else {
                      alert("失败");
                      return;
                    }
                  },
                });
              });
              type_td.append(alert_a);
              type_td.append(span);

              type_td.append(delete_a);
              type_td.append(span2);

              type_td.append(alert_default_a);
            }




            let tr = $("<tr></tr>");
            tr.addClass(table_color_array[randomNum(0, 7)]);
            tr.append(accept_td);
            tr.append(province_td);
            tr.append(address_td);
            tr.append(telphone_td);
            tr.append(type_td);

            $("#address_tbody").append(tr);

          }
        }
      },
    });
  }

  //设置修改地址的按钮事件
  $("#alert_address_btn").click(function () {

    if (isDisabled("#alert_address_btn")) {
      return;
    }


    //获取要修改的地址id
    let id = $("#quit_btn").val();

    //获取收件人
    let accept = $("#alert_accept_name").val();

    //获取省
    let province = provinceList[$("#province").val() - 1].name;

    //获取城市
    let city = provinceList[$("#province").val() - 1].cityList[$("#city").val()].name;

    //获取区
    let area = provinceList[$("#province").val() - 1].cityList[$("#city").val()].areaList[$("#area").val()];

    //详细地址
    let address = $("#alert_address_now").val();

    //电话
    let telphone = $("#alert_telphone").val();

    //如果一样 说明没有修改 则不向服务器发送数据
    if (old_accept == accept && old_province == province && old_city == city
      && old_area == area && old_telphone == telphone && old_address_td == address) {
      console.log("数据没有变化 不发送请求");
      $("#address_model").modal('hide');
      return;
    }
    //更新地址
    $.ajax({
      type: "POST",
      url: "/woniumall2/address/updateAddress",
      data: {
        id: id,
        accept: accept,
        province: province,
        city: city,
        area: area,
        address: address,
        telphone: telphone
      },
      success: function (responseResult) {
        console.log(responseResult);
        //如果修改成功
        if (responseResult.status == "UPDATE_ADDRESS_SUCCESS") {
          $("#address_model").modal('hide');
          //调用方法获取table
          addAddressTable();

        } else {
          alert("系统繁忙 稍后再试");
          $("#address_model").modal('hide');
        }
      },
    })
  });
  //退出修改地址的模糊框
  //
  $("#quit_btn").click(function () {
    quit_alert_address();
  });

  function quit_alert_address() {
    $("#alert_telphone").removeClass("is-invalid");
    $("#alert_telphone").addClass("is-valid");
    $("#alert_address_btn").removeClass("disabled");
    $("#alert_telphone_tips").removeClass("invalid-feedback");
    $("#alert_telphone_tips").text("");
  }

  //打开地址修改
  $("#add_btn").click(function () {
    if (isDisabled("#add_btn")) {
      return;
    }

    $("#add_btn").hide(0);
    $("#add_btn").addClass('fade disabled');
    $("#add_div").removeClass('fade disabled');
    $("#add_div").show(0);


    console.log("正在被点击");
  });

  //取消修改地址
  $("#add_cancel").click(function () {
    $("#add_btn").removeClass('fade disabled');
    $("#add_btn").show();
    $("#add_div").addClass('fade disabled');
    $("#add_div").hide(0);
  })

  //保存地址
  $("#sub_address").click(function () {

    if (isDisabled("#sub_address")) {
      return;
    }

    let accept = $("#name_input").val();

    //获取省
    let province = provinceList[$("#add_address_province").val()].name;
    console.log(province);
    //获取城市
    let city = provinceList[$("#add_address_province").val()].cityList[$("#add_address_city").val()].name;


    //获取区
    let area = provinceList[$("#add_address_province").val()].cityList[$("#add_address_city").val()].areaList[$("#add_address_area").val()];

    //街道地址
    let address = $("#address_input").val();

    let telphone = $("#telphone_input").val();

    let type = "";
    if ($("#default_input").prop("checked")) {
      type = "y";
    } else {
      type = "n";
    }
    $("#name_input").val("");

    $("#add_address_province").val("");

    $("#add_address_city").val("");

    $("#add_address_area").val("");

    $("#address_input").val("");

    $("#telphone_input").val("");

    $("#default_input").prop("checked", false);

    $.ajax({
      type: "POST",
      url: "/woniumall2/address/addAddress",
      data: {
        oldId: old_address,
        accept: accept,
        province: province,
        city: city,
        area: area,
        address: address,
        telphone: telphone,
        type: type
      },
      success: function (responseResult) {
        console.log(responseResult);
        if (responseResult.status == "ADD_ADDRESS_SUCCRSS") {
          alert("添加成功");
          addAddressTable();
          $("#add_btn").show();
          $("#add_btn").removeClass('fade disabled');
          $("#add_div").addClass('fade disabled');
          $("#add_div").hide();
        } else if (responseResult.status == "ADD_ADDRESS_FAIL") {
          alert("添加失败 稍后再试");
        }

      },
    });
  })

  //alert_accept_name
  //提示姓名不能为空
  $("#alert_accept_name").on("input", function () {
    let name_input = $("#name_input").val();
    if (name_input.length == 0) {
      //tips(#name_input,#sub_address,name_input_tips)
      //input变色
      $("#alert_accept_name").removeClass("is-valid");
      $("#alert_accept_name").addClass("is-invalid");

      //按钮不可点击
      $("#alert_address_btn").addClass("disabled");

      //提示信息
      $("#alert_accept_name_tips").addClass("invalid-feedback");
      $("#alert_accept_name_tips").text("姓名不能为空");
    } else {

      $("#alert_accept_name").removeClass("is-invalid");
      $("#alert_accept_name").addClass("is-valid");

      //按钮不可点击
      $("#alert_address_btn").removeClass("disabled");

      //提示信息
      $("#alert_accept_name_tips").removeClass("invalid-feedback");
      $("#alert_accept_name_tips").text("");
    }
  });

  //电话提示
  $("#alert_telphone").on("input", function () {
    telphone_rex("#alert_telphone", "#alert_address_btn", "#alert_telphone_tips");
  });

  //收货地址不能为空

  $("#name_input").on("input", function () {
    let name_input = $("#name_input").val();
    if (name_input.length == 0) {
      //tips(#name_input,#sub_address,name_input_tips)
      //input变色
      $("#name_input").addClass("is-invalid");

      //按钮不可点击
      $("#sub_address").addClass("disabled");

      //提示信息
      $("#name_input_tips").addClass("invalid-feedback");
      $("#name_input_tips").text("姓名不能为空");
    } else {

      $("#name_input").removeClass("is-invalid");
      $("#name_input").addClass("is-valid");

      //按钮不可点击
      $("#sub_address").removeClass("disabled");

      //提示信息
      $("#name_input_tips").removeClass("invalid-feedback");
      $("#name_input_tips").text("");
    }
  });

  //电话号码必须满足11位
  $("#telphone_input").on("input", function () {
    telphone_rex("#telphone_input", "#sub_address", "#telphone_input_tips");
  });

  function telphone_rex(telphone_name, btn_name, telphone_tips) {
    let telphone = $(telphone_name).val();
    let telphone_re = /^\d{11}$/;
    if (telphone_re.test(telphone)) {

      $(telphone_name).removeClass("is-invalid");
      $(telphone_name).addClass("is-valid");
      $(btn_name).removeClass("disabled");
      $(telphone_tips).removeClass("invalid-feedback");
      $(telphone_tips).text("");
    } else {
      $(telphone_name).addClass("is-invalid");
      $(btn_name).addClass("disabled");
      $(telphone_tips).text("电话号码只能是数字和11位字符")
      $(telphone_tips).addClass("invalid-feedback");

    }
  }


});



